package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.AdlZhsq;
import me.zhengjie.business.domain.Hljg;
import me.zhengjie.business.domain.Zhsq;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.repository.*;
import me.zhengjie.business.service.ZhsqHomeService;
import me.zhengjie.business.service.dto.ZhsqDto;
import me.zhengjie.business.service.dto.ZhsqQueryCriteria;
import me.zhengjie.business.service.mapstruct.ZhsqMapper;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.modules.system.domain.vo.GsglScale;
import me.zhengjie.modules.system.repository.GsglScaleRepository;
import me.zhengjie.repository.LocalStorageRepository;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lyl
 * @since 2023/10/19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ZhsqHomeServiceImpl implements ZhsqHomeService {
    private final ZhsqRepository zhsqRepository;
    private final HljgRepository hljgRepository;
    private final GsglRepository gsglRepository;
    private final GsglScaleRepository gsglScaleRepository;

    private final ZhsqMapper zhsqMapper;

    private final LocalStorageRepository localStorageRepository;
    private final AdlZhsqRepository adlZhsqRepository;

    @PersistenceContext
    private EntityManager em;

    @Override
    public Page<Zhsq> queryAll(ZhsqQueryCriteria criteria, Pageable pageable){
        Page<Zhsq> page = zhsqRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return page;
    }

    @Override
    public ZhsqDto createZhsqHome(Zhsq resources, String ids) {

        log.info("PC端[ZhsqServiceImpl - create]新增照护申请 {} ", resources);

        Long userid = SecurityUtils.getCurrentUserId();
        int age = CalculateAge.getCurrentAge(resources.getBisZhsqSnrySfz());

        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        String sbgsId = gsgl.getBisGsglId() == null ? "" : gsgl.getBisGsglId();
        Hljg hljg = hljgRepository.findById(gsgl.getBisGsglId()).orElseGet(Hljg::new);
        resources.setHljg(hljg);
        resources.setBisZhsqHljgBm(hljg.getBisGsglYljgdm());

        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());
        resources.setBisSbgsId(sbgsId);
        resources.setBisPggsId(sbgsId);
        resources.setBisUserId(userid);
        resources.setBisZhsqNl(String.valueOf(age));
        resources.setBisZhsqSnryXb("1".equals(resources.getBisZhsqSnryXb()) ? "女" : "男");

        log.info("[MpZhsqServiceImpl - create]照护类别：居家自主护理[03]{} ");
        resources.setBisZhsqZhlb("03");

        String fs = resources.getBisZhsqAdl();
        log.info("[ZhsqServiceImpl - create]--------------- 居家新增照护申请 - 保存ADL量表评分 - {}", fs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

        String sndj = snMap.get(GetSndj.SNDJ);

        log.info("[ZhsqServiceImpl - create]--------------- 居家新增照护申请 - 失能等级 - {}", sndj);
        resources.setBisZhsqSndj(sndj);

        resources.setBisZhsqAdlPc("40288a8880efbadb0180efbd9b410000");
        // 新增adl量表
        Zhsq newZhsq = zhsqRepository.save(resources);
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(newZhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
        }

        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 关联附件 ");
            String[] picIds = ids.split(",");
            for (String picId:picIds) {
                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }

        return zhsqMapper.toDto(newZhsq);
    }

    @Override
    @Transactional
    public ZhsqDto updateZhsq(Zhsq resources,String ids) {
        log.info("PC端[ZhsqServiceImpl - create]新增照护申请 {} ", resources);

        Long userid = SecurityUtils.getCurrentUserId();
        int age = CalculateAge.getCurrentAge(resources.getBisZhsqSnrySfz());

        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());
        String sbgsId = gsgl.getBisGsglId() == null ? "" : gsgl.getBisGsglId();

        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());
        resources.setBisSbgsId(sbgsId);
        resources.setBisPggsId(sbgsId);
        resources.setBisUserId(userid);
        resources.setBisZhsqNl(String.valueOf(age));
        resources.setBisZhsqSnryXb("1".equals(resources.getBisZhsqSnryXb()) ? "女" : "男");

        log.info("[MpZhsqServiceImpl - create]照护类别：居家自主护理[03]{} ");
        resources.setBisZhsqZhlb("03");
        Zhsq zhsq = zhsqRepository.findById(resources.getBisZhsqId()).orElseGet(Zhsq::new);
        ValidationUtil.isNull( zhsq.getBisZhsqId(),"Zhsq","id",resources.getBisZhsqId());
        zhsq.copy(resources);

        adlZhsqRepository.deleteAdlByZhid(resources.getBisZhsqId());
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(zhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
        }
        String fs = resources.getBisZhsqAdl();
        log.info("[ZhsqServiceImpl - update]--------------- 居家修改照护申请 - 保存ADL量表评分 - {}", fs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

        String sndj = snMap.get(GetSndj.SNDJ);

        log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请 - 失能等级 - {}", sndj);

        zhsq.setBisZhsqSndj(sndj);

        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqServiceImpl - update]--------------- 机构修改照护申请机构修改照护申请 - 关联附件 ");

            String[] picIds = ids.split(",");
            for (String picId:picIds) {

                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(resources.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }
        return zhsqMapper.toDto(zhsqRepository.save(zhsq));
    }

    @Override
    public ZhsqDto submitZhsqHome(Zhsq resources, String ids) {
        log.info("PC端[ZhsqServiceImpl - create]新增照护申请 {} ", resources);

        Long userid = SecurityUtils.getCurrentUserId();
        int age = CalculateAge.getCurrentAge(resources.getBisZhsqSnrySfz());

        Gsgl gsgl = gsglRepository.queryGsgl(SecurityUtils.getCurrentUserId());

        String sbgsId = gsgl.getBisGsglId() == null ? "" : gsgl.getBisGsglId();

        // 先获取实体中的ADL量表信息
        List<AdlZhsq> list = resources.getAdlZhsqs();
        // 清空实体中ADL量表信息
        resources.setAdlZhsqs(new ArrayList<>());
        resources.setBisSbgsId(sbgsId);
        resources.setBisPggsId(sbgsId);
        resources.setBisUserId(userid);
        resources.setBisZhsqNl(String.valueOf(age));
        resources.setBisZhsqSnryXb("1".equals(resources.getBisZhsqSnryXb()) ? "女" : "男");

        log.info("[MpZhsqServiceImpl - create]照护类别：居家自主护理[03]{} ");
        resources.setBisZhsqZhlb("03");

        String fs = resources.getBisZhsqAdl();
        log.info("[ZhsqServiceImpl - create]--------------- 居家新增照护申请 - 保存ADL量表评分 - {}", fs);

        Map<String, String> snMap = GetSndj.analyse(Integer.parseInt(fs), Integer.parseInt(resources.getBisZhsqNl()));

        String sndj = snMap.get(GetSndj.SNDJ);

        log.info("[ZhsqServiceImpl - create]--------------- 居家新增照护申请 - 失能等级 - {}", sndj);
        resources.setBisZhsqSndj(sndj);

        resources.setBisZhsqAdlPc("40288a8880efbadb0180efbd9b410000");
        // 新增adl量表
        Zhsq newZhsq = zhsqRepository.save(resources);
        for (int i = 0; i < list.size(); i++) {
            AdlZhsq adl = list.get(i);
            adl.setBisAdlZhsqId(IdUtil.simpleUUID());
            adl.setZhsq(newZhsq);
            adl.setBisUserId(userid);
            adlZhsqRepository.save(adl);
        }

        // 新增照片
        if(ids != null && !ids.equals("")){
            log.info("[ZhsqServiceImpl - create]--------------- 机构新增照护申请 - 关联附件 ");
            String[] picIds = ids.split(",");
            for (String picId:picIds) {
                Long storage_id = Long.parseLong(picId);
                LocalStorage localStorage = localStorageRepository.findById(storage_id).orElseGet(LocalStorage::new);
                localStorage.setYwid(String.valueOf(newZhsq.getBisZhsqId()));
                localStorageRepository.save(localStorage);
            }
        }

        return zhsqMapper.toDto(newZhsq);
    }
}
